package upload

import (
	"errors"
	"github.com/gogf/gf/frame/g"
	"mime/multipart"
	"github.com/gogf/gf/container/garray"
	"strings"
)

type FileSystem interface {
	Upload(file *multipart.FileHeader) (filepath string, key string, err error)
	Delete(key string) error
}

func Storage() FileSystem {
	switch g.Cfg().Get("filesystem.default") {
	case "local":
		return Local
	case "minio":
		if result, err := MinioInit(); err != nil {
			g.Log().Error("function Minio.init() Failed!", g.Map{"err": err})
			return nil
		} else {
			return result
		}
	case "aliyun":
		if result, err := AliYunInit(); err != nil {
			g.Log().Error("function AliYun.init() Failed!", g.Map{"err": err})
			return nil
		} else {
			return result
		}
	case "tencent":
		return TencentCos
	default:
		return Local
	}
}

// 验证上传文件
func VerifyFile (upload_type string, file *multipart.FileHeader) error{
	// 判断文件大小
	maxSize := g.Cfg().GetString("filesystem.config." + upload_type + ".maxSize")
	if maxSize > file.Filename {
		return errors.New("文件大小超出上传限制, 限制值:" + maxSize)
	}
	// 判断文件类型
	extensions := g.Cfg().GetArray("filesystem.config." + upload_type + ".extensions")
	extName := file.Filename[strings.LastIndex(file.Filename, "."):]
	if garray.NewArrayFrom(extensions).Contains(extName) == false {
		return errors.New("文件类型不允许")
	}
	return nil
}
